package com.xiaomazi.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xiaomazi.edu.entity.Subject;
import com.xiaomazi.edu.excel.SubjectData;
import com.xiaomazi.edu.service.SubjectService;
import com.xiaomazi.servicebase.exception.LLXYException;

/**
 * @program: llxy-parent
 * @description: Excel的监听器
 * @author: 小马子
 * @create: 2023-02-14 17:28
 **/
public class ExcelListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;

    public ExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /*读取excel内容，一行一行进行读取*/
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (null == data) throw new LLXYException(20001,"Excel读取失败,文件数据为空");

        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        if (!existOneSubject(data.getOneSubjectName())){
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(data.getOneSubjectName());
            subjectService.save(subject);
        }

        String parentId = subjectService.query().eq("title", data.getOneSubjectName()).one().getId();
        if (!existTwoSubject(data.getTwoSubjectName(),parentId)){
            Subject subject = new Subject();
            subject.setTitle(data.getTwoSubjectName());
            subject.setParentId(parentId);
            subjectService.save(subject);
        }

    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    private boolean existOneSubject(String name){
        return subjectService.query().eq("title", name).one() != null;
    }

    private boolean existTwoSubject(String name,String pid){
        return subjectService.query().eq("title", name).eq("parent_id",pid).one() != null;
    }

}
